import json
import datetime

from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from sqlalchemy.orm.attributes import QueryableAttribute

from .core import app

db = SQLAlchemy(app)
migrate = Migrate(app, db)


class UserStatus:
    ISOLATION = '隔离'
    NOT_ISOLATION = '非隔离'
    RETURN = '今日返京'


class BaseModel(db.Model):
    __abstract__ = True

    def to_dict(self, show=None, _hide=None, _path=None):
        """Return a dictionary representation of this model."""

        show = show or []

        _hide = _hide or []
        hidden = self._hidden_fields if hasattr(self, "_hidden_fields") else []
        default = self._default_fields if hasattr(self, "_default_fields") else []
        default.extend(['id', 'modified_at', 'created_at'])

        if not _path:
            _path = self.__tablename__.lower()

            def prepend_path(item):
                item = item.lower()
                if item.split(".", 1)[0] == _path:
                    return item
                if len(item) == 0:
                    return item
                if item[0] != ".":
                    item = ".%s" % item
                item = "%s%s" % (_path, item)
                return item

            _hide[:] = [prepend_path(x) for x in _hide]
            show[:] = [prepend_path(x) for x in show]

        columns = self.__table__.columns.keys()
        relationships = self.__mapper__.relationships.keys()
        properties = dir(self)

        ret_data = {}

        for key in columns:
            if key.startswith("_"):
                continue
            check = "%s.%s" % (_path, key)
            if check in _hide or key in hidden:
                continue
            if check in show or key in default:
                value = getattr(self, key)
                if key.endswith('_time') and isinstance(value, datetime.datetime):
                    ret_data[key] = value.strftime('%Y-%m-%d %H:%M')
                elif isinstance(value, datetime.date):
                    ret_data[key] = value.strftime('%Y-%m-%d')
                else:
                    ret_data[key] = value

        for key in relationships:
            if key.startswith("_"):
                continue
            check = "%s.%s" % (_path, key)
            if check in _hide or key in hidden:
                continue
            if check in show or key in default:
                _hide.append(check)
                is_list = self.__mapper__.relationships[key].uselist
                if is_list:
                    items = getattr(self, key)
                    if self.__mapper__.relationships[key].query_class is not None:
                        if hasattr(items, "all"):
                            items = items.all()
                    ret_data[key] = []
                    for item in items:
                        ret_data[key].append(
                            item.to_dict(
                                show=list(show),
                                _hide=list(_hide),
                                _path=("%s.%s" % (_path, key.lower())),
                            )
                        )
                else:
                    if (
                            self.__mapper__.relationships[key].query_class is not None
                            or self.__mapper__.relationships[key].instrument_class
                            is not None
                    ):
                        item = getattr(self, key)
                        if item is not None:
                            ret_data[key] = item.to_dict(
                                show=list(show),
                                _hide=list(_hide),
                                _path=("%s.%s" % (_path, key.lower())),
                            )
                        else:
                            ret_data[key] = None
                    else:
                        ret_data[key] = getattr(self, key)

        for key in list(set(properties) - set(columns) - set(relationships)):
            if key.startswith("_"):
                continue
            if not hasattr(self.__class__, key):
                continue
            attr = getattr(self.__class__, key)
            if not (isinstance(attr, property) or isinstance(attr, QueryableAttribute)):
                continue
            check = "%s.%s" % (_path, key)
            if check in _hide or key in hidden:
                continue
            if check in show or key in default:
                val = getattr(self, key)
                if hasattr(val, "to_dict"):
                    ret_data[key] = val.to_dict(
                        show=list(show),
                        _hide=list(_hide),
                        _path=('%s.%s' % (_path, key.lower())),
                    )
                else:
                    try:
                        ret_data[key] = json.loads(json.dumps(val))
                    except:
                        pass

        return ret_data

    def update_from_dict(self, d):
        for k, v in d.items():
            if k not in self._update_fields:
                continue
            elif hasattr(self, k):
                if v is not None:
                    if k.endswith('_date'):
                        v = datetime.datetime.strptime(v, '%Y-%m-%d').date()
                    elif k.endswith('_time'):
                        v = datetime.datetime.strptime(v, '%Y-%m-%d %H:%M')
                try:
                    setattr(self, k, v)
                except Exception as ex:
                    raise ex
        return self


class Roles:
    USER = 'User'
    GROUP_MANAGER = 'GroupManager'
    ADMIN = 'Admin'

    DEPARTMENT_MANAGER = 'DepartmentManager'
    DEPARTMENT_ADMINISTRATOR = 'DepartmentAdmin'

    DEPARTMENT_USERS = [DEPARTMENT_MANAGER, DEPARTMENT_ADMINISTRATOR, ADMIN]


class Group(BaseModel):
    __tablename__ = 'user_group'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(64), unique=True)
    secret = db.Column(db.String(64))

    _default_fields = ['name']


class User(BaseModel):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    number = db.Column(db.String(32), unique=True, nullable=False)
    password = db.Column(db.String(64), nullable=False)
    salt = db.Column(db.String(64), nullable=False)

    # Roles
    role = db.Column(db.String(64), nullable=False)

    group_id = db.Column(db.Integer, db.ForeignKey('user_group.id'), nullable=False)
    group = db.relationship('Group', backref=db.backref('users', lazy=True))

    name = db.Column(db.String(16))
    phone = db.Column(db.String(32))
    comment = db.Column(db.String(32))

    department_number = db.Column(db.String(4), db.ForeignKey('dwdm.dm'))
    department = db.relationship('Dwdm', backref=db.backref('users', lazy=True))

    weixin_id = db.Column(db.String(128), nullable=True, unique=True)

    _update_fields = ['name', 'phone', 'comment']

    _default_fields = ['number', 'role'] + _update_fields


class DailyState(BaseModel):
    __tablename__ = 'daily_state'
    __table_args__ = (db.UniqueConstraint('day', 'user_id'),)

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    day = db.Column(db.Date)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user = db.relationship('User', backref=db.backref('states', lazy=True))

    status = db.Column(db.String(32), nullable=False)
    comment = db.Column(db.String(128))
    fill_time = db.Column(db.DateTime, nullable=False)

    category = db.Column(db.String(32), nullable=False)
    office_type = db.Column(db.String(32), nullable=True)
    addr_type = db.Column(db.String(32), nullable=False)

    health = db.Column(db.String(16))
    health_detail = db.Column(db.String(32))

    temperature_morning = db.Column(db.Float(precision=1))
    temperature_middle = db.Column(db.Float(precision=1))
    temperature_night = db.Column(db.Float(precision=1))

    # for isolation
    has_co_isolation_14 = db.Column(db.Boolean)
    need_water_count = db.Column(db.Integer)
    need_medical = db.Column(db.String(255))
    need_tool = db.Column(db.String(255))
    need_vegetable = db.Column(db.Boolean)
    need_express = db.Column(db.String(255))

    # for non-isolation
    address_changed = db.Column(db.Boolean)
    has_coron_in_region = db.Column(db.Boolean)

    # for return
    # 返京出发时间
    departure_date = db.Column(db.Date)
    # 实际到达时间
    arrival_date = db.Column(db.Date)
    return_traffic = db.Column(db.String(32))
    exit_reason = db.Column(db.String(16))
    isolation_address = db.Column(db.String(128))
    is_hubei = db.Column(db.Boolean)

    # for outside
    will_return = db.Column(db.Boolean, nullable=False)
    current_address = db.Column(db.String(255))
    return_date_fixed = db.Column(db.Boolean)
    plan_return_date = db.Column(db.Date)
    plan_traffic = db.Column(db.String(32))

    _update_fields = ['status', 'comment',
                      'category', 'office_type', 'addr_type',
                      'health', 'health_detail',
                      'temperature_morning', 'temperature_middle', 'temperature_night',
                      'has_co_isolation_14',
                      'need_water_count', 'need_medical', 'need_tool', 'need_vegetable', 'need_express',
                      'address_changed', 'has_coron_in_region',
                      'departure_date', 'arrival_date', 'return_traffic',
                      'exit_reason', 'isolation_address', 'is_hubei',
                      'will_return', 'current_address', 'return_date_fixed', 'plan_return_date', 'plan_traffic']
    _default_fields = ['day', 'fill_time'] + _update_fields

    @classmethod
    def display_columns(cls):
        return cls._default_fields

    @property
    def is_temperature_normal(self):
        return (not self.temperature_morning or self.temperature_morning < 37) \
               and (not self.temperature_middle or self.temperature_middle < 37) \
               and (not self.temperature_night or self.temperature_night < 37)


class OutsideReturn(BaseModel):
    __tablename__ = 'outside_return'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user = db.relationship('User', backref=db.backref('outside_returns', lazy=True))

    health = db.Column(db.String(16))
    health_detail = db.Column(db.String(32))

    fill_time = db.Column(db.DateTime)

    current_address = db.Column(db.String(255))
    return_date_fixed = db.Column(db.Boolean)
    plan_return_date = db.Column(db.Date)
    plan_traffic = db.Column(db.String(32))
    plan_isolation_address = db.Column(db.String(64))

    approval_id = db.Column(db.Integer, db.ForeignKey('approval.id'))
    approval = db.relationship('Approval', uselist=False, backref=db.backref('outside_return', lazy=True))

    _update_fields = ['health', 'health_detail', 'current_address', 'return_date_fixed', 'plan_return_date',
                      'plan_traffic', 'plan_isolation_address', 'fill_time']
    _default_fields = ['id'] + _update_fields


class Route(BaseModel):
    __tablename__ = 'route'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    daily_state_id = db.Column(db.Integer, db.ForeignKey('daily_state.id'), nullable=False)
    daily_state = db.relationship('DailyState', backref=db.backref('routes', lazy=True))

    source = db.Column(db.String(32), nullable=False)
    target = db.Column(db.String(32), nullable=False)
    source_date = db.Column(db.Date, nullable=False)

    _update_fields = ['source', 'target', 'source_date']
    _default_fields = ['id'] + _update_fields


class LeaveAddrType:
    OFFICE = 'Office'
    SOUTH = 'South'
    NORTH = 'North'


class Leave(BaseModel):
    __tablename__ = 'leave'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user = db.relationship('User', backref=db.backref('leaves', lazy=True))

    # LeaveAddrType
    addr_type = db.Column(db.String(32), nullable=False)
    order_time = db.Column(db.DateTime, nullable=False)

    is_in = db.Column(db.Boolean, nullable=False)
    is_single = db.Column(db.Boolean, nullable=False)

    leave_time = db.Column(db.DateTime, nullable=False)
    return_time = db.Column(db.DateTime, nullable=False)
    reason = db.Column(db.String(64), nullable=False)

    traffic = db.Column(db.String(32), nullable=False)
    location = db.Column(db.String(64), nullable=False)
    persons = db.Column(db.String(1024))

    approval_id = db.Column(db.Integer, db.ForeignKey('approval.id'))
    approval = db.relationship('Approval', uselist=False, backref=db.backref('leave', lazy=True))

    _update_fields = ['addr_type', 'is_in', 'is_single',
                      'leave_time', 'return_time', 'reason',
                      'traffic', 'location', 'persons']
    _default_fields = ['id', 'order_time'] + _update_fields


class CoPerson(BaseModel):
    __tablename__ = 'co_person'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    daily_state_id = db.Column(db.Integer, db.ForeignKey('daily_state.id'))
    daily_state = db.relationship('DailyState', backref=db.backref('co_persons', lazy=True))

    outside_return_id = db.Column(db.Integer, db.ForeignKey('outside_return.id'))
    outside_return = db.relationship('OutsideReturn', backref=db.backref('co_persons', lazy=True))

    relation = db.Column(db.String(32), nullable=False)
    detail = db.Column(db.String(32))
    health = db.Column(db.String(32), nullable=False)
    health_detail = db.Column(db.String(128))
    temperature = db.Column(db.Float(precision=1))

    _update_fields = ['relation', 'detail', 'health', 'health_detail', 'temperature']
    _default_fields = ['id'] + _update_fields


class Token(BaseModel):
    __tablename__ = 'token'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    token = db.Column(db.String(64), unique=True, index=True, nullable=False)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user = db.relationship('User', backref=db.backref('tokens', lazy=True))

    issue_time = db.Column(db.DateTime, nullable=False)
    expire_time = db.Column(db.DateTime, nullable=False)


class Publication(BaseModel):
    __tablename__ = 'publication'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    publish_time = db.Column(db.DateTime)
    content = db.Column(db.Text(65535))

    _update_fields = ['publish_time', 'content']
    _default_fields = ['id'] + _update_fields


class ApprovalStates:
    # 等待组长审批
    WAIT_GROUP = 'WAIT_GROUP'
    # 等待管理员审批
    WAIT_ADMIN = 'WAIT_ADMIN'
    # 完成审批
    COMPLETED = 'COMPLETED'
    # 组长驳回
    REJECT_GROUP = 'REJECT_GROUP'
    # 管理员驳回
    REJECT_ADMIN = 'REJECT_ADMIN'


class Approval(BaseModel):
    __tablename__ = 'approval'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    fill_time = db.Column(db.DateTime, nullable=False)

    state = db.Column(db.String(32), nullable=False)

    group_manager_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    group_manager = db.relationship('User', backref=db.backref('group_approvals', lazy=True),
                                    foreign_keys=[group_manager_id])

    admin_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    admin = db.relationship('User', backref=db.backref('admin_approvals', lazy=True),
                            foreign_keys=[admin_id])

    _default_fields = ['id', 'fill_time', 'state']
    _update_fields = []


# 单位代码
class Dwdm(BaseModel):
    __tablename__ = 'dwdm'

    dm = db.Column(db.String(4), primary_key=True)

    mc = db.Column(db.String(20), nullable=False, unique=True)
    # 单位足地省份
    zdsf = db.Column(db.String(10), nullable=False)
    ifwh = db.Column(db.Boolean, nullable=False)
    gbsl = db.Column(db.Integer, nullable=False)
    zssl = db.Column(db.Integer, nullable=False)
    wzsl = db.Column(db.Integer, nullable=False)
    zgsl = db.Column(db.Integer, nullable=False)

    _update_fields = ['mc', 'zdsf', 'ifwh', 'gbsl', 'zssl', 'wzsl', 'zgsl']
    _default_fields = ['dm'] + _update_fields


# 在岗在位表
class Zwdm(BaseModel):
    __tablename__ = 'zwdm'

    # 上学、借调、事假、病假、休假未离京、休假离京
    dm = db.Column(db.String(1), primary_key=True)
    mc = db.Column(db.String(32), nullable=False, unique=True)
    ifzw = db.Column(db.Boolean)  # 是否在位

    _update_fields = ['mc', 'ifzw']
    _default_fields = ['dm'] + _update_fields


# 隔离点表
class Gld(BaseModel):
    __tablename__ = 'gld'

    dm = db.Column(db.String(2), primary_key=True)

    dwdm = db.Column(db.String(4), db.ForeignKey('dwdm.dm'))
    dw = db.relationship('Dwdm', backref=db.backref('glds', lazy=True))

    dz = db.Column(db.String(40), nullable=False)
    fzr = db.Column(db.String(6), nullable=False)
    dh = db.Column(db.String(30), nullable=False)

    _update_fields = ['dz', 'fzr', 'dh', 'dwdm']
    _default_fields = ['dm'] + _update_fields


# 健康状况代码表
class Ztdm(BaseModel):
    __tablename__ = 'ztdm'
    dm = db.Column(db.String(1), primary_key=True)
    mc = db.Column(db.String(10), nullable=False, )

    _update_fields = ['mc']
    _default_fields = ['dm'] + _update_fields


class Zwinfo(BaseModel):
    __tablename__ = 'zwinfo'
    __table_args__ = (db.UniqueConstraint('day', 'dwdm', 'lxdm'),)

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    dwdm = db.Column(db.String(4), db.ForeignKey('dwdm.dm'), nullable=False)
    dw = db.relationship('Dwdm', backref=db.backref('zwinfos', lazy=True))

    lxdm = db.Column(db.String(1), db.ForeignKey('zwdm.dm'), nullable=False)
    lx = db.relationship('Zwdm', backref=db.backref('zwinfos', lazy=True))

    day = db.Column(db.Date, nullable=False)
    sl = db.Column(db.Integer, nullable=False)

    _update_fields = ['dwdm', 'lxdm', 'sl', 'day']
    _default_fields = ['id'] + _update_fields


# related person
class Ry(BaseModel):
    __tablename__ = 'ry'

    sfzh = db.Column(db.String(18), primary_key=True)

    dwdm = db.Column(db.String(4), db.ForeignKey('dwdm.dm'))
    dw = db.relationship('Dwdm', backref=db.backref('rys', lazy=True))

    xm = db.Column(db.String(6), nullable=False)
    sex = db.Column(db.String(1), nullable=False)  # 男女
    age = db.Column(db.Integer, nullable=False)
    lb = db.Column(db.String(4), nullable=False)
    dwmc = db.Column(db.String(30), nullable=False)
    # 是否休假
    ifxj = db.Column(db.Boolean, nullable=False)
    ifqz = db.Column(db.String(1), nullable=False)
    qz_details = db.Column(db.String(255))
    zz = db.Column(db.String(40), nullable=True)  # 住址
    dh = db.Column(db.String(30), nullable=False)  # 联系电话

    ifgl = db.Column(db.Boolean)
    ifgtgl = db.Column(db.Boolean)

    _update_fields = ['dwdm', 'xm', 'sex', 'age', 'lb', 'dwmc', 'ifxj', 'ifqz', 'zz', 'dh', 'ifgl', 'ifgtgl', 'qz_details']
    _default_fields = ['sfzh'] + _update_fields


class Xjinfo(BaseModel):
    __tablename__ = 'xjinfo'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    sfzh = db.Column(db.String(18), db.ForeignKey('ry.sfzh'), nullable=False)
    ry = db.relationship('Ry', backref=db.backref('xjinfos', lazy=True))
    # 休假地点
    sf = db.Column(db.String(10))  # 休假省份
    xs = db.Column(db.String(10))  # 休假县市
    dz = db.Column(db.String(10))  # 休假地址
    ld_date = db.Column(db.Date)  # 离队日期
    gd_date = db.Column(db.Date)  # 归队日期
    jtgj = db.Column(db.String(20), nullable=True)  # 交通工具多选：高铁、列车、飞机、汽车、自驾车
    hb = db.Column(db.String(30), nullable=True)  # 班次
    glfs = db.Column(db.String(32), nullable=True)  # 隔离方式:A:居家，B: 集中
    glddm = db.Column(db.String(2), db.ForeignKey('gld.dm'), nullable=True)  # 隔离点代码
    gld = db.relationship('Gld', backref=db.backref('xjinfos', lazy=True))  # 隔离点
    gldz = db.Column(db.String(30), nullable=True)  # 隔离点详细地点
    glqs_date = db.Column(db.Date, nullable=True)  # 隔离结束日期
    gljs_date = db.Column(db.Date, nullable=True)  # 健康状况代码
    dh = db.Column(db.String(30))

    ztdm = db.Column(db.String(1), db.ForeignKey('ztdm.dm'), nullable=False)
    zt = db.relationship('Ztdm', backref=db.backref('xjinfos', lazy=True))

    bz = db.Column(db.String(30))

    _update_fields = ['status', 'comment',
                      'sf', 'xs', 'dz', 'ld_date', 'gd_date', 'jtgj', 'hb', 'glfs',
                      'glddm', 'gldz', 'glqs_date', 'gljs_date', 'ztdm', 'bz',
                      'dh']
    _default_fields = ['id'] + _update_fields

    @classmethod
    def display_columns(cls):
        return cls._default_fields


# related person
class Friend(BaseModel):
    __tablename__ = 'friend'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    sfzh = db.Column(db.String(18), db.ForeignKey('ry.sfzh'))
    ry = db.relationship('Ry', backref=db.backref('friends', lazy=True))

    dwdm = db.Column(db.String(4), db.ForeignKey('dwdm.dm'))
    dw = db.relationship('Dwdm', backref=db.backref('friends', lazy=True))

    xm = db.Column(db.String(6), nullable=False)  # 家属姓名
    gx = db.Column(db.String(6), nullable=False)  # 关系
    sex = db.Column(db.String(1), nullable=False)  # 性别
    age = db.Column(db.Integer, nullable=False)  # 年龄
    ifqz = db.Column(db.String(1)) # 是否确诊
    zz = db.Column(db.String(40), nullable=True)  # 住址
    dh = db.Column(db.String(30), nullable=True)  # 联系电话

    ifgl = db.Column(db.Boolean, nullable=False)  # 是否隔离
    glfs = db.Column(db.String(32), nullable=True)  # 隔离方式 A:居家，B: 集中，C:住院
    glddm = db.Column(db.String(2), db.ForeignKey('gld.dm'), nullable=True)  # 隔离点代码
    gld = db.relationship('Gld', backref=db.backref('friends', lazy=True))  # 隔离点
    gldz = db.Column(db.String(30), nullable=True)  # 隔离点详细地点
    glqs_date = db.Column(db.Date, nullable=True)  # 隔离结束日期
    gljs_date = db.Column(db.Date, nullable=True)  # 健康状况代码

    _update_fields = ['xm', 'gx', 'sex', 'age', 'ifgl', 'zz', 'dh', 'glfs', 'glddm',
                      'gldz', 'glqs_date', 'gljs_date']
    _default_fields = ['id'] + _update_fields


# 密切接触者
class Jcz(BaseModel):
    __tablename__ = 'jcz'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    sfzh = db.Column(db.String(18), db.ForeignKey('ry.sfzh'))
    ry = db.relationship('Ry', backref=db.backref('jczs', lazy=True))

    lb = db.Column(db.String(2), nullable=False)  # 干部、战士、文职、职工、离退休人员、其他人员
    dwmc = db.Column(db.String(30), nullable=False)  # 部职别
    xm = db.Column(db.String(32), nullable=False)  # 姓名
    gx = db.Column(db.String(32), nullable=False)  # 关系
    sex = db.Column(db.String(1), nullable=False)  # 性别
    age = db.Column(db.Integer, nullable=False)  # 年龄
    ifqz = db.Column(db.String(1), nullable=False)  # 是否确诊或疑似
    zz = db.Column(db.String(40))  # 住址
    dh = db.Column(db.String(30), nullable=False)  # 联系电话

    ifgl = db.Column(db.Boolean, nullable=False)  # 是否隔离
    glfs = db.Column(db.String(32), nullable=True)  # 隔离方式 A:居家，B: 集中，C:住院

    glddm = db.Column(db.String(2), db.ForeignKey('gld.dm'), nullable=True)  # 隔离点代码
    gld = db.relationship('Gld', backref=db.backref('jczs', lazy=True))  # 隔离点

    gldz = db.Column(db.String(30), nullable=True)  # 隔离点详细地点
    glqs_date = db.Column(db.Date, nullable=True)  # 隔离结束日期
    gljs_date = db.Column(db.Date, nullable=True)  # 健康状况代码

    _update_fields = ['lb', 'dwmc', 'xm', 'gx', 'sex', 'age', 'ifqz', 'zz', 'dh',
                      'ifgl', 'glfs', 'glddm', 'gldz', 'glqs_date', 'gljs_date']
    _default_fields = ['id'] + _update_fields


# 责任人员
class Fzr(BaseModel):
    __tablename__ = 'fzr'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)

    dwdm = db.Column(db.String(4), db.ForeignKey('dwdm.dm'))
    dw = db.relationship('Dwdm', backref=db.backref('fzrs', lazy=True))

    name = db.Column(db.String(6), nullable=False)  # 姓名
    tel = db.Column(db.String(30), nullable=False)  # 联系电话
    zw = db.Column(db.String(30), nullable=True)  # 职务

    _update_fields = ['name', 'tel', 'zw', 'swdm']
    _default_fields = ['id'] + _update_fields
